import router from './index'
import http from '../utils/request'
import { auth, menu } from '../api'
import { userStore } from '../store/modules/user'
import { getData, goLogin, recursion } from '../utils/auth'

const apiBase = import.meta.env.VITE_APP_BASE_API
const appUrl = import.meta.env.VITE_APP_API

const whiteList = ['/login'] // 白名单

function getUrlKey(name: String) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || ['', ''])[1].replace(/\+/g, '%20')) || null
}

router.beforeEach((to: { fullPath: string }, _from: any, next: () => void) => {
    // to and from are both route objects. must call `next`.
    const token = getData('token') ? getData('token') : ''
    if (token) {
        next()
    } else {
        const ticket = getUrlKey('ticket')
        if (ticket) {
            // 此处验证ticket
            const parmas = {
                ticket,
                service: apiBase + '/redirect?client=' + appUrl
            }
            http.post(auth, parmas).then(res => {
                userStore.store.dispatch('setToken', res.data.token)
                const attributes = res.data.attributes
                http.get(menu).then(res => {
                    const sideMenu = recursion(res.data)
                    attributes.menuTrees = sideMenu

                    userStore.store.dispatch('setUserInfo', attributes)
                    userStore.store.dispatch('setMainInfo', sideMenu)
                    window.location.href = window.location.origin + window.location.pathname
                    next()
                })
            })
            return
        }

        if (whiteList.indexOf(to.fullPath) !== -1) {
            next()
        } else {
            goLogin(0)
        }
    }
})